package cn.com.haopy.yue.ai.wx.utils;

import com.alibaba.fastjson.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AIChatParseDataUtil {

    //input最多字符串长度
    public static final Integer AiInputLenghth = 256;

    /**
     * AI数据解析
     */
    public static JSONObject json2Obj(String answer) {
        try {

            JSONObject json = null;

            Pattern pattern = Pattern.compile("```json");

            Matcher matcher = pattern.matcher(answer);

            boolean isMatch = matcher.find();

            if (isMatch) {
                String answerJson = answer.split("```json")[1].replace("```", "");
                json = JSONObject.parseObject(answerJson);
            } else {
                pattern = Pattern.compile("</think>");
                matcher = pattern.matcher(answer);
                isMatch = matcher.find();
                if (isMatch) {
                    String answerThink = answer.split("</think>")[1];
                    json = JSONObject.parseObject(answerThink);
                } else {
                    //都不包含
                    json = JSONObject.parseObject(answer);
                }
            }
            //json 为空不解析
            return json;


        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


}
